<?php

namespace web\common\utils;

/**
* 逻辑
*/
class MealLogic {

    //分配释放
    public function equipType($order_list, $equipOrderM, $equipM, $balanceM, $recordM, $accountM, $sysParameterM, $forLogM, $logicC){

        foreach ($order_list as $value){
            if($value['type'] == 1){       //体验任务包
                $re = $this->equipType1($value, $equipOrderM, $equipM, $balanceM, $recordM, $accountM, $sysParameterM, $forLogM, $logicC);
            }else if($value['type'] == 2){ // 孵化任务包
                $re = $this->equipType2($value, $equipOrderM, $equipM, $balanceM, $recordM, $accountM, $sysParameterM, $forLogM, $logicC);
            }else if($value['type'] == 3){ // DC任务包
                $re = $this->equipType3($value, $equipOrderM, $equipM, $balanceM, $recordM, $accountM, $sysParameterM, $forLogM, $logicC);
            }else if($value['type'] == 4){ // KOF任务包
                $re = $this->equipType4($value, $equipOrderM, $equipM, $balanceM, $recordM);
            }
        }
        return true;
    }

    // 1-体验任务包
    public function equipType1($order_data, $equipOrderM, $equipM, $balanceM, $recordM, $accountM, $sysParameterM, $forLogM, $logicC){
//        $order_data = $equipOrderM->getDetail(60578);
        $config_data = $equipM->getDetail($order_data['e_id']);

        //1、释放金额

        //算出还剩多少额度
        $remaining_amount = $order_data['total_amount'] - $order_data['total_release'];
        //本次释放的额度
        $amount = $order_data['days_release'];
        if($remaining_amount < $order_data['days_release']){
            $amount = $remaining_amount;
        }

        if($amount > 0){
            $re_balance = $balanceM->updateBalance($order_data['user_id'], $order_data['release_balance_type'], $amount, true);
            if(!$re_balance){
                return false;
            }
            $re_record = $recordM->addRecord($order_data['user_id'], $amount, $re_balance['before_amount'], $re_balance['amount'], $order_data['release_balance_type'], 200, 1, 0, '任务包释放('.$config_data['equip_name'].')');
            if(!$re_record){
                return false;
            }
            //2、扣除订单额度
            $update_data = [
                'total_release' => ($order_data['total_release'] + $amount),
                'day_release' => $amount,
                'update_time' => date("Y-m-d H:i:s"),
            ];
            //如果今天的领完
            if($order_data['total_amount'] <= ($order_data['total_release'] + $amount)){
                $update_data['status'] = 1;
            }
            $re = $equipOrderM->where(['id' => $order_data['id']])->update($update_data);
            if(!$re){
                return false;
            }
            $pid = $accountM->getPID($order_data['user_id']);
            if($pid > 0){
                $is_order = $equipOrderM->isOrder($pid);
                //3、发出直推分享奖
                if($is_order > 0){
                    $first_push = $sysParameterM->getValByName('first_push');
                    $share_amount = round(($amount * $first_push / 100), 4);
                    if($share_amount > 0){
                        $re = $forLogM->addRecord($pid, $order_data['user_id'], $order_data['release_balance_type'], 201, $share_amount, '直推奖励('.$config_data['equip_name'].')');
                        if(!$re){
                            return false;
                        }
                    }
                }
                //4、团队收益管理奖（极差 平级是当前的等级的所有连着的平分 奖励1%的总额）
                if ($amount > 0) {
                    $re = (new \addons\equip\model\TeamRevenueAward())->addData($pid, $order_data['user_id'], $order_data['release_balance_type'], $amount, '团队收益管理奖('.$config_data['equip_name'].')');
//                    $re = $logicC->leadershipAward($pid, $order_data['user_id'], $order_data['release_balance_type'], $amount);
                    if (!$re) {
                        return false;
                    }
                }
            }
        }

        return true;
    }

    // 2-孵化任务包（USDT）
    public function equipType2($order_data, $equipOrderM, $equipM, $balanceM, $recordM, $accountM, $sysParameterM, $forLogM, $logicC){
//        $order_data = $equipOrderM->getDetail(60559);
        $config_data = $equipM->getDetail($order_data['e_id']);
        //1、释放金额

        //算出还剩多少额度
        $remaining_amount = $order_data['total_amount'] - $order_data['total_release'];
        //本次释放的额度
        $amount = $order_data['days_release'];
        if($remaining_amount < $order_data['days_release']){
            $amount = $remaining_amount;
        }

        if($amount > 0){
            $usdt_price = $sysParameterM->getValByName('usdt_price');
            $dc_price = $sysParameterM->getValByName('dc_price');

            $dc_amount = round(($amount * $usdt_price / $dc_price) , 4);

            $re_balance = $balanceM->updateBalance($order_data['user_id'], $order_data['release_balance_type'], $dc_amount, true);
            if(!$re_balance){
                return false;
            }
            $re_record = $recordM->addRecord($order_data['user_id'], $dc_amount, $re_balance['before_amount'], $re_balance['amount'], $order_data['release_balance_type'], 200, 1, 0, '任务包释放('.$config_data['equip_name'].')');
            if(!$re_record){
                return false;
            }
            //2、扣除订单额度
            $update_data = [
                'total_release' => ($order_data['total_release'] + $amount),
                'day_release' => $amount,
                'update_time' => date("Y-m-d H:i:s"),
            ];
            //如果今天的领完
            if($order_data['total_amount'] <= ($order_data['total_release'] + $amount)){
                $update_data['status'] = 1;
            }
            $re = $equipOrderM->where(['id' => $order_data['id']])->update($update_data);
            if(!$re){
                return false;
            }

            //3、发出直推分享奖
            $pid = $accountM->getPID($order_data['user_id']);
            if($pid > 0){
                $is_order = $equipOrderM->isOrder($pid);
                if($is_order > 0) {
                    $first_push = $sysParameterM->getValByName('first_push');
                    $share_amount = round(($dc_amount * $first_push / 100), 4);
                    if ($share_amount > 0) {
                        $re = $forLogM->addRecord($pid, $order_data['user_id'], $order_data['release_balance_type'], 201, $share_amount, '直推奖励('.$config_data['equip_name'].')');
                        if (!$re) {
                            return false;
                        }
                    }
                }
                //4、团队收益管理奖（极差 平级是当前的等级的所有连着的平分 奖励1%的总额）
                if ($dc_amount > 0) {
                    $re = (new \addons\equip\model\TeamRevenueAward())->addData($pid, $order_data['user_id'], $order_data['release_balance_type'], $dc_amount, '团队收益管理奖('.$config_data['equip_name'].')');

//                    $re = $logicC->leadershipAward($pid, $order_data['user_id'], $order_data['release_balance_type'], $dc_amount);
                    if (!$re) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    // 3-DC任务包
    public function equipType3($order_data, $equipOrderM, $equipM, $balanceM, $recordM, $accountM, $sysParameterM, $forLogM, $logicC){

//        $order_data = $equipOrderM->getDetail(60571);
        $config_data = $equipM->getDetail($order_data['e_id']);

        //1、释放金额

        //算出还剩多少额度
        $remaining_amount = $order_data['total_amount'] - $order_data['total_release'];
        //本次释放的额度
        $amount = $order_data['days_release'];
        if($remaining_amount < $order_data['days_release']){
            $amount = $remaining_amount;
        }

        if($amount > 0) {
            $dc_price = $sysParameterM->getValByName('dc_price');
            $kof_price = $sysParameterM->getValByName('kof_price');

            $kof_amount = round(($amount * $dc_price / $kof_price), 4);

            $re_balance = $balanceM->updateBalance($order_data['user_id'], $order_data['release_balance_type'], $kof_amount, true);
            if (!$re_balance) {
                return false;
            }
            $re_record = $recordM->addRecord($order_data['user_id'], $kof_amount, $re_balance['before_amount'], $re_balance['amount'], $order_data['release_balance_type'], 200, 1, 0, '任务包释放(' . $config_data['equip_name'] . ')');
            if (!$re_record) {
                return false;
            }
            //2、扣除订单额度
            $update_data = [
                'total_release' => ($order_data['total_release'] + $amount),
                'day_release' => $amount,
                'update_time' => date("Y-m-d H:i:s"),
            ];
            //如果今天的领完
            if ($order_data['total_amount'] <= ($order_data['total_release'] + $amount)) {
                $update_data['status'] = 1;
            }
            $re = $equipOrderM->where(['id' => $order_data['id']])->update($update_data);
            if (!$re) {
                return false;
            }

            //3、发出直推分享奖
            $pid = $accountM->getPID($order_data['user_id']);
            if ($pid > 0) {
                $is_order = $equipOrderM->isOrder($pid);
                if ($is_order > 0) {
                    $first_push = $sysParameterM->getValByName('first_push');
                    $share_amount = round(($kof_amount * $first_push / 100), 4);
                    if ($share_amount > 0) {
                        $re = $forLogM->addRecord($pid, $order_data['user_id'], $order_data['release_balance_type'], 201, $share_amount, '直推奖励(' . $config_data['equip_name'] . ')');
                        if (!$re) {
                            return false;
                        }
                    }

                }
                //4、团队收益管理奖（极差 平级是当前的等级的所有连着的平分 奖励1%的总额）
                if ($kof_amount > 0) {

                    $re = (new \addons\equip\model\TeamRevenueAward())->addData($pid, $order_data['user_id'], $order_data['release_balance_type'], $kof_amount, '团队收益管理奖('.$config_data['equip_name'].')');

//                    $re = $logicC->leadershipAward($pid, $order_data['user_id'], $order_data['release_balance_type'], $kof_amount);
                    if (!$re) {
                        return false;
                    }
                }
            }

        }
        return true;
    }

    // 4-KOF任务包',
    public function equipType4($order_data, $equipOrderM, $equipM, $balanceM, $recordM){
//        $order_data = $equipOrderM->getDetail(60573);
        $config_data = $equipM->getDetail($order_data['e_id']);

        //1、释放金额

        //算出还剩多少额度
        $remaining_amount = $order_data['total_amount'] - $order_data['total_release'];
        //本次释放的额度
        $amount = $order_data['days_release'];
        if($remaining_amount < $order_data['days_release']){
            $amount = $remaining_amount;
        }

        if($amount > 0) {
            $re_balance = $balanceM->updateBalance($order_data['user_id'], $order_data['release_balance_type'], $amount, true);
            if (!$re_balance) {
                return false;
            }
            $re_record = $recordM->addRecord($order_data['user_id'], $amount, $re_balance['before_amount'], $re_balance['amount'], $order_data['release_balance_type'], 200, 1, 0, '任务包释放(' . $config_data['equip_name'] . ')');
            if (!$re_record) {
                return false;
            }
            //2、扣除订单额度
            $update_data = [
                'total_release' => ($order_data['total_release'] + $amount),
                'day_release' => $amount,
                'update_time' => date("Y-m-d H:i:s"),
            ];
            //如果今天的领完
            if ($order_data['total_amount'] <= ($order_data['total_release'] + $amount)) {
                $update_data['status'] = 1;
            }
            $re = $equipOrderM->where(['id' => $order_data['id']])->update($update_data);
            if (!$re) {
                return false;
            }
        }
        return true;
    }

    /**
     *
     * 团队收益管理奖
     * @param $pid          上级用户
     * @param $user_id      发起人
     * @param $balance_type 发放币种
     * @param $amount       发起金额
     * @param $max_level    最大等级
     * @param string $remark       备注
     * @param int $use_rate     上一次的比率
     * @param int $is_peers     是否拿过平级
     * @param int $last_level   上次等级
     * @param int $issue_use_rate   上次发放的金额比率
     * @param array $peers_arr_user_id  平级奖的用户ID
     * @param int $peers_total_amount  平级奖的总金额
     * @return bool
     */
    public function leadershipAward($pid, $user_id, $balance_type, $amount, $max_level, $remark = '团队收益管理奖', $use_rate = 0, $is_peers = 0, $last_level = 0,$issue_use_rate=0, $peers_arr_user_id = [], $peers_total_amount = 0){
        if($pid > 0){
            $levelConfigM = new \addons\member\model\LevelConfig();
            $accountM = new \addons\member\model\MemberAccountModel();
            //获取用户的对应动态收益等级数据
            $user_level_data = $levelConfigM->getLevel($pid);
            if($user_level_data){

                //如果是平级奖励
                if($user_level_data['level'] > 2){
//                    if($user_level_data['level'] == $last_level && $is_peers == 0){
                    //如果当前用户等级小于 已到达的等级  视为跳过当前已发放等级的平级奖
//                    dump($user_level_data['level']);
                    if($user_level_data['level'] == $last_level){
                        //动态平级奖励比率
                        $sysParaM = new \web\common\model\sys\SysParameterModel();
                        $peers_tax = $sysParaM->getValByName('peers_tax');
                        //本次获得的金额
                        $obtain_amount = $amount * $peers_tax / 100;
                        $peers_total_amount = $obtain_amount;
                        array_push($peers_arr_user_id, $pid);
//                        $is_peers = 1;
                    }else if($user_level_data['level'] > $last_level){
                        //更高一级
                        //本次获得的金额
                        $obtain_amount = $amount * ($user_level_data['release_revenue_rate'] - $use_rate) / 100;

                        //发放动态释放团队奖
                        $re = $this->leadershipAwardReward($pid, $user_id, $obtain_amount, $balance_type, $remark);
                        if(!$re) {
                            return false;
                        }

                        $issue_use_rate = $user_level_data['release_revenue_rate'] - $use_rate;
                        $use_rate = $user_level_data['release_revenue_rate'];
                        $last_level = $user_level_data['level'];

                        if($peers_arr_user_id){
//                            dump($peers_arr_user_id);echo '--';dump($peers_total_amount);die;
                            $peers_amount = round(($peers_total_amount / count($peers_arr_user_id)), 4);
                            foreach ($peers_arr_user_id as $value){
                                //发放动态释放团队奖
                                $re = $this->leadershipAwardReward($value, $user_id, $peers_amount, $balance_type, $remark);
                                if(!$re) {
                                    return false;
                                }
                            }
                            $peers_arr_user_id = [];
                            $peers_total_amount = 0;
                        }
//                        $is_peers = 0;
                    }
//                    dump($peers_arr_user_id);
                    if($user_level_data['level'] < $last_level){
//                        $is_peers = 1;
                        if($peers_arr_user_id){
                            $peers_amount = round(($peers_total_amount / count($peers_arr_user_id)), 4);
                            foreach ($peers_arr_user_id as $value){
                                //发放动态释放团队奖
                                $re = $this->leadershipAwardReward($value, $user_id, $peers_amount, $balance_type, $remark);
                                if(!$re) {
                                    return false;
                                }
                            }
                            $peers_arr_user_id = [];
                            $peers_total_amount = 0;
                        }
                        $last_level = $user_level_data['level'];
                    }
                }
//                dump($max_level);die;
                if($last_level == $max_level && $user_level_data['level'] < $max_level){
                    if($peers_arr_user_id){
                        $peers_amount = round(($peers_total_amount / count($peers_arr_user_id)), 4);
                        foreach ($peers_arr_user_id as $value){
                            //发放动态释放团队奖
                            $re = $this->leadershipAwardReward($value, $user_id, $peers_amount, $balance_type, $remark);
                            if(!$re) {
                                return false;
                            }
                        }
                        $peers_arr_user_id = [];
                        $peers_total_amount = 0;
                    }
                }
            }
            $pp_id = $accountM->getPID($pid);

            if($pp_id > 0){
                $this->leadershipAward($pp_id, $user_id, $balance_type, $amount, $max_level, $remark, $use_rate, $is_peers, $last_level, $issue_use_rate,$peers_arr_user_id, $peers_total_amount);
            }
        }
        return true;
    }

    /**
     * 发放团队收益管理奖
     * @param $pid
     * @param $user_id
     * @param $amount
     * @param $balance_type
     * @param $remark
     * @return bool
     */
    public function leadershipAwardReward($pid, $user_id, $amount, $balance_type, $remark = ''){
        //发放中奖者奖励  奖励UMK勋章
//        $balanceM = new \addons\member\model\Balance();
//        $recordM = new \addons\member\model\TradingRecord();

        $equipOrderM = new \addons\equip\model\EquipOrder();
        $is_order = $equipOrderM->isOrder($pid);
        if($is_order > 0){
            $forLogM = new \addons\member\model\RewardForLog();
            $re = $forLogM->addRecord($pid, $user_id, $balance_type, 202, $amount, $remark);

//            $re_balance = $balanceM->updateBalance($pid, $balance_type, $amount, true);
//            $re_record = $recordM->addRecord($pid, $amount, $re_balance['before_amount'], $re_balance['amount'], $balance_type, 202, 1, $user_id, '团队收益管理奖');
            if(!$re){
                return false;
            }
        }
        return true;
    }

    /**
     * 请求外网注册
     * @param $url
     * @param $tel
     * @param $id
     * @param $tid
     * @param $password
     * @param string $key
     */
    public function getNetworkReg($url, $tel, $id, $tid, $password, $key='ScuNmjkBRZq4a7rgDnFWfea8KxN74OxH'){
        $data['tel'] = $tel;
        $data['id'] = $id;
        $data['tid'] = $tid;
        $data['password'] = $password;
        $data['sign']=md5($data['tel'].$data['id'].$data['tid'].$data['password'].$key);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  FALSE);
        $output = curl_exec($ch);
        curl_close($ch);
        $jsoninfo = json_decode($output, true);
        dump($jsoninfo);
    }


}

?>
